package trabalho.doo3.j2me.telas;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
import trabalho.doo3.j2me.bean.Reserva;
import trabalho.doo3.j2me.bean.Usuario;
import trabalho.doo3.j2me.midlet.Midlet;

/**
 *
 * @author Matheus
 */
public class TelaLogin extends Form implements CommandListener {

    private Midlet midlet;
    private Command btSair;
    private Command btLogar;
    private Usuario user;
    private Reserva r;
    public TextField login, senha;
    private boolean logado = false;
    private String URL = "http://localhost:8080/Trabalho_DOO_III_-_Web_Server/servlet";

    public TelaLogin(String title, Midlet midlet) {
        super(title);
            this.midlet = midlet;
            this.btSair = new Command("Sair", Command.EXIT, 0);
            this.addCommand(btSair);
            this.btLogar = new Command("Logar", Command.ITEM, 1);
            this.addCommand(btLogar);
            login = new TextField("Login", "", 64, TextField.ANY);
            this.append(login);
            senha = new TextField("Senha", "", 64, TextField.ANY);
            this.append(senha);
            this.setCommandListener(this);
    }

    public void commandAction(Command c, Displayable d) {
        Display display = Display.getDisplay(midlet);
        if (c == btSair) {
            midlet.destroyApp(true);
            midlet.notifyDestroyed();
        } else if (c == btLogar) {
            String login = this.login.getString();
            String senha = this.senha.getString();
            if (login.equals("") || senha.equals("")) {
                Alert alert = new Alert("Erro");
                alert.setString("Você deve preencher todos os campos.");
                display.setCurrent(alert);
            } else {
                conexaoWWW();
            }
            if (logado) {
                try {
                    r = new Reserva();
                    r.clear();
                } catch (RecordStoreException ex) {
                    ex.printStackTrace();
                }
                addReserva();
                display = Display.getDisplay(midlet);
                TelaReservas telaLogin = new TelaReservas("Tela de Reservas", midlet, login);
                display.setCurrent(telaLogin);
            } else {
            }
        }

    }

    private void conexaoWWW() {
        HttpConnection httpConn = null;
        try {
            httpConn = (HttpConnection) Connector.open(URL, Connector.READ_WRITE);
            httpConn.setRequestMethod(HttpConnection.POST);
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
            httpConn.setRequestProperty("Content-Language", "pt-BR");
            httpConn.setRequestProperty("Accept", "application/octet-stream");
            httpConn.setRequestProperty("Connection", "close");
            OutputStream os = httpConn.openOutputStream();
            String l = "&usuario=" + login.getString();
            String s = "&senha=" + senha.getString();
            os.write("acao=login".getBytes());
            os.write(l.getBytes());
            os.write(s.getBytes());
            os.close();
            String msg = httpConn.getResponseMessage();
            int code = httpConn.getResponseCode();
            if (code == httpConn.HTTP_OK) {
                DataInputStream dis = httpConn.openDataInputStream();
                String leitura = null;
                do {
                    leitura = dis.readUTF();
                    user = new Usuario();
                    try {
                        user.open();
                        user.insert(leitura);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    } catch (RecordStoreException ex) {
                        ex.printStackTrace();
                    }
                    if (!"#Encerra leitura#".equals(leitura)) {
                        if (leitura.equalsIgnoreCase("0")) {
                            logado = false;
                        } else {
                            logado = true;
                        }
                    }
                } while (!"#Encerra leitura#".equals(leitura) && leitura != null);
                dis.close();
            } else {
                System.out.println("Código invalido: " + msg);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void addReserva() {
        HttpConnection httpConn = null;
        try {
            httpConn = (HttpConnection) Connector.open(URL, Connector.READ_WRITE);
            httpConn.setRequestMethod(HttpConnection.POST);
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
            httpConn.setRequestProperty("Content-Language", "pt-BR");
            httpConn.setRequestProperty("Accept", "application/octet-stream");
            httpConn.setRequestProperty("Connection", "close");
            OutputStream os = httpConn.openOutputStream();
            String l = "&usuario=" + login.getString();
            os.write("acao=select_reservas".getBytes());
            os.write(l.getBytes());
            os.close();
            String msg = httpConn.getResponseMessage();
            int code = httpConn.getResponseCode();
            if (code == httpConn.HTTP_OK) {
                DataInputStream dis = httpConn.openDataInputStream();
                String leitura = null;
                String usuario = null;
                r = new Reserva();
                do {
                    leitura = dis.readUTF();
                    if (!"#Encerra leitura#".equals(leitura)) {
                        try {
                            r.open();
                            r.setFilme_id(leitura);
                            r.setDeletar("nao");
                            r.insert(r);
                            r.close();
                        } catch (RecordStoreNotOpenException ex) {
                            ex.printStackTrace();
                        } catch (RecordStoreException ex) {
                            ex.printStackTrace();
                        }
                    }
                } while (!"#Encerra leitura#".equals(leitura) && leitura != null);
                dis.close();
            } else {
                System.out.println("Código invalido: " + msg);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
